package com.example.simpletask

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.*
import android.widget.*
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.HORIZONTAL
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date

class AddActivity : AppCompatActivity() {

//    弹出菜单
    private var popupWindow: PopupWindow? = null
//    弹出菜单的样式，即对应activity_popupwindow.xml这个文件
    private var icontentView: View? = null

    lateinit var dbHelper: DbHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add)
//        弹出菜单要在页面加载时就渲染好，但是是在看不到的地方，按钮点击后只是通过动画移动到可以看见的地方
        showPopwindow()
        dbHelper = DbHelper(this)

//        通过recyclerView渲染步骤选择器
        val layoutManager = LinearLayoutManager(this)
        val stepsSelectors = findViewById<RecyclerView>(R.id.stepsSelectorsArea)
        stepsSelectors.layoutManager = layoutManager
        layoutManager.orientation = HORIZONTAL
        val stepsAdapter = StepsSelectorAdapter(1)
        stepsSelectors.adapter = stepsAdapter

//        确认按钮，点击后将页面数据读取，并将数据存入数据库，然后跳转到主页面
        val confirmBtn = findViewById<ImageButton>(R.id.confirmBtn)
        confirmBtn.setOnClickListener {
            val contentInput = findViewById<EditText>(R.id.contentInput)
            var content = contentInput.text.toString()
            var steps = stepsAdapter.getSteps()
            if (content == "") {
                Toast.makeText(this, "任务内容不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val m = Mission(content, steps)
            dbHelper.insertMission(m.getId(), content, steps)
            MainActivity.start(this)
        }

//        取消按钮，什么都不干直接跳转到主页面
        val cancelBtn = findViewById<ImageButton>(R.id.cancelBtn)
        cancelBtn.setOnClickListener {
            MainActivity.start(this)
        }

//        相机按钮，点击后打开弹出菜单
        val cameraBtn = findViewById<ImageButton>(R.id.cameraBtn)
        cameraBtn.setOnClickListener {
            openPopWindow()
        }
    }

    // 按下android回退物理键 PopipWindow消失解决
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            if (popupWindow != null && popupWindow!!.isShowing) {
                popupWindow!!.dismiss()
                return true
            }
        }
        return false
    }

    lateinit var imageUri: Uri
    lateinit var outputImage: File
    val takePhoto: Int = 0
    val fromAlbum: Int = 1
    /**
     * 显示popupWindow
     */
    private fun showPopwindow() {
        //加载弹出框的布局
        icontentView = LayoutInflater.from(this@AddActivity).inflate(
            R.layout.activity_popupwindow, null  //111
        )
        popupWindow = PopupWindow(
            icontentView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        popupWindow!!.isFocusable = true
        //取得焦点
        popupWindow!!.setBackgroundDrawable(BitmapDrawable())
        //点击外部消失
        popupWindow!!.isOutsideTouchable = true
        //设置可以点击
        popupWindow!!.isTouchable = true
        //进入退出的动画，指定刚才定义的style
        popupWindow!!.animationStyle = R.style.ipopwindow_anim_style

        /**
         * 以下几个都是弹出菜单的按钮
         */

        val takePhotoBtn : Button = popupWindow!!.contentView.findViewById(R.id.takePhotoBtn)
        takePhotoBtn.setOnClickListener {
            val timeStamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
            // 创建File 对象，用于存储拍照后的照片
            outputImage = File(externalCacheDir,"image_" + timeStamp + ".jpg")
            if (outputImage.exists()){
                outputImage.delete()
            }
            outputImage.createNewFile()

            imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                FileProvider.getUriForFile(this,
                    "com.example.simpletask.fileprovider", outputImage)
            }else{
                Uri.fromFile(outputImage)
            }
            // 启动相机程序
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)
            startActivityForResult(intent, takePhoto)
        }

        val fromAlbumBtn : Button = popupWindow!!.contentView.findViewById(R.id.fromAlbumBtn)
        fromAlbumBtn.setOnClickListener {
            // 打开文件选择器
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            // 指定只显示图片
            intent.type = "image/*"
            startActivityForResult(intent, fromAlbum)
        }

        val deletePhotoBtn: Button = popupWindow!!.contentView
            .findViewById(R.id.deletePictureBtn)
        deletePhotoBtn.setOnClickListener {
//            点击删除时会首先弹出个对话框询问是否真的删除
            val alertDialog = AlertDialog.Builder(this).apply {
                setMessage("是否确定要删除?")
                setPositiveButton("确定") { dialog, which ->
                    val imageView = findViewById<ImageView>(R.id.imageView)
                    imageView.setImageBitmap(null)
                }
                setNegativeButton("取消") { dialog, which ->
                }
            }.show()

//            将两个按钮改变颜色，否则默认是白色显示不出来
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                .setTextColor(resources.getColor(R.color.red))
            alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                .setTextColor(resources.getColor(R.color.black))
        }
    }

    /**
     * 按钮的监听
     * @param v
     */
    fun openPopWindow() {
        //从底部显示
        popupWindow!!.showAtLocation(icontentView, Gravity.BOTTOM, 0, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode){
            takePhoto ->{
                if (resultCode == Activity.RESULT_OK) {
                    // 将拍摄的照片显示出来
                    val bitmap =
                        BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                    val imageView: ImageView = findViewById(R.id.imageView)
                    imageView.setImageBitmap(rotateIfRequired(bitmap))
                    saveBitmap(bitmap)
                }
            }
            fromAlbum ->{
                if (resultCode == Activity.RESULT_OK && data != null){
                    data.data?.let { uri ->
                        val bitmap = getBitmapFromUri(uri)
                        val imageView: ImageView = findViewById(R.id.imageView)
                        imageView.setImageBitmap(bitmap)
                    }
                }
            }
        }
    }

    private fun getBitmapFromUri(uri: Uri) = contentResolver.openFileDescriptor(uri,"r")?.use {
        BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
    }

    private fun rotateIfRequired(bitmap: Bitmap): Bitmap {
        val exif = ExifInterface(outputImage.path) // 实例化图片信息类
        val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
        // 拿取图片的旋转角度,模式为标准顺时针。
        return when(orientation){
            ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap,90)
            ExifInterface.ORIENTATION_ROTATE_180 ->rotateBitmap(bitmap,180)
            ExifInterface.ORIENTATION_ROTATE_270 ->rotateBitmap(bitmap,270)
            else -> bitmap
        }
    }

    private fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap {
        val matrix = Matrix()  // 矩阵对象
        matrix.postRotate(degree.toFloat()) // 顺时针旋转角度
        val rotatedBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.width,bitmap.height,matrix,true)
        // 截取图片并且使用矩阵对象旋转图片，同时也截取原图片
        bitmap.recycle() // 将不再需要的Bitmap 对象回收
        return rotatedBitmap
    }

    private fun saveBitmap(bmp: Bitmap)
    {
        var tags="saveBitmap"
        var f = System.currentTimeMillis() .toString()+ ".jpg"
        val path = Environment.getExternalStorageDirectory().toString() + "/DCIM/"
        val file:File = File(path + f)
        var fos: FileOutputStream? = null;
        try {
            fos = FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            Log.d(tags,"saved!")
        } catch (e:Exception) {
            Log.d(tags,"error!"+e.message)
        } finally {
            fos?.flush()
            fos?.close()
        }
    }
}
